// Contact management application w/Firbase v1.1
// full CRUD on contacts
// GET, POST, DELETE, PUT

var myContacts = (function () {

    var contactsObj = [];    // array of all contacts
    var contactsKey = [];   // containr for the contact
    var contactToUpdate;    // contain the Firebase Id of the current contact

    /* Contacts Constructor --------------------------------------------------------------------------- */
    function Contact(fName, lName, phone, email) {
        this.firstName = fName,
        this.lastName = lName,
        this.phone = phone,
        this.email = email
    }

    /* GET --------------------------------------------------------------------------- */
    // PRIVATE - Get contacts from Firebase
    function getFirebaseContacts() {

        var myTimer = setInterval(function () {
            console.log("timer");
        }, 15000);

        var myStopTimer = setTimeout(function(){
            clearInterval(myTimer);
            console.log("myStopTimer")
        }, 1000);

        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'https://315demo.firebaseio.com/contacts/.json', true);
        xhr.send();
        xhr.onload = function () { // success
            if (this.status >= 200 && this.status < 400) {
                var myData = JSON.parse(this.response);
                console.log("getFirebaseContacts SUCCESS");
                showFbContent(myData);
            }
            else { // error
                console.log("You have an error!!");
            }
        }
    };

    // render FB content to screen
    function showFbContent(tData) {
        var tCnt;                   // temp Contact 
        var tStr = "";              // temp string used for concat
        var tRes = $("#tableResults");   // element to render content
        tRes.empty();               // clear the html
        contactsObj = [];           // clear the object
        contactsKey = [];           // clear the keys

        var headerString = '<tr><td>ID</td><td>Name</td><td>Email</td><td>Phone</td><td>Actions</td></tr>';
        tRes.append(headerString);
        //
        contactsKey = Object.keys(tData); // grab the keys and asign to array
        //console.log(keysArr);
        var counter = 0;
        var contactObj; // contact object from the constructor
        for (var i in tData) {
            var contact = tData[i];
            // Action buttons
            var editBtn = '<button  onclick="myContacts.doEdit(' + counter + ')" type="button" class="btn btn-default btn-sm"> <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>Edit</button>'
            var deleteBtn = '<button onclick="myContacts.doDelete(' + counter + ' , myCbSuccess, myCbError)" type="button" class="btn btn-default btn-sm"> <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>Delete</button>'
            // creating a new Contact object
            contactObj = new Contact(contact.fname, contact.lname, contact.phone, contact.email);
            // add it (newly created Contacts object) to the array
            contactsObj.push(contactObj);
            // render to screen
            tStr = "";              // clear the temp string
            tStr += "<tr>";
            tStr += "<td>" + counter + "</td>";
            tStr += "<td>" + contact.fname + " " + contact.lname + "</td>";
            tStr += "<td>" + contact.phone + "</td>";
            tStr += "<td>" + contact.email + "</td>";
            tStr += "<td>" + editBtn + " " + deleteBtn + "</td>"
            tStr += "</tr>"
            counter++;
            tRes.append(tStr);
        }
    }
    /* ADD --------------------------------------------------------------------------- */
    // Adds a contact to FireBase via AJAX
    function addBuilder() {
        addFirebaseContact()
    }
    function addFirebaseContact(successCallback, errorCallback) {
        var fName = $("#cFname").val();
        var lName = $("#cLname").val();
        var userName = fName + lName;
        var tPhone = $("#cPhone").val();
        var tEmail = $("#cEmail").val();
        console.log(fName, lName, tPhone, tEmail);
        var objToPost = {
            "fname": fName,
            "lname": lName,
            "email": tEmail,
            "phone": tPhone,
            "userName": userName

        }
        /*
{"joesmith": {
"fname": "Joey",
"lname": "Smithers",
"email": "ok@ok.com",
"phone": "5555555"
}
}
*/
        // AJAX call for POST
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'https://315demo.firebaseio.com/contacts/.json', true);
        xhr.onload = function () {
            if (this.status >= 200 && this.status < 400) {
                if(successCallback && typeof(successCallback)== "function"){
                    successCallback()
                    errorCallback()
                }
                //console.log("Success!", this.response)
                getFirebaseContacts();
            } else {
                // err
            }
        }
        // convert the Object to String
        var strObject = JSON.stringify(objToPost);
        xhr.send(strObject);
    }
    /* DELETE --------------------------------------------------------------------------- */
    // xhr for deleting a contact
    function deleteBuilder(id) {
        console.log("hit deleteBuilder")
        goFirebaseDelete(cId, mySuccess, myErr)

    }
    function goFirebaseDelete(cId, cbSuccess, cbError) {
        //alert(contactsKey[cId]);
        var xhr = new XMLHttpRequest();
        xhr.open('DELETE', 'https://315demo.firebaseio.com/contacts/' + contactsKey[cId] + '/.json', true)
        xhr.onload = function () {
            if (this.status >= 200 && this.status < 400) {
                if(cbSuccess && typeof(cbSuccess)== "function"){
                    cbSuccess();
                }
            } else {//error
                if (cbError && typeof (cbError) == "function") {
                }
            }
        }
        function mySuccess() {
            console.log("hit my success")
            getFirebaseContacts();
        }
        function myErr() {
            console.log("nailed it")
        }

        xhr.send();
    }
    function myCbSuccess() {
        console.log("SUCCESS FROM THE CALLBACK")
        getFirebaseContacts();
    }
    function myCbError() {
        alert("error!");
    }

    /* UPDATE --------------------------------------------------------------------------- */
    // populate & show the modal
    function showEditDialog(tempId) {
        // save the ID to local variable
        contactToUpdate = contactsKey[tempId];
        // create temp object of Contact in array (based on index argument)
        var tContact = contactsObj[tempId];
        //populate the fields
        $('#uFname').val(tContact.firstName);
        $('#uLname').val(tContact.lastName);
        $('#uPhone').val(tContact.phone);
        $('#uEmail').val(tContact.email);
        $('#myEditModal').modal("show");
        //
        console.log(contactsObj);
        console.log(contactsKey);

    }
    // save the contents of the modal
    function updateFirebaseContact() {
        var name = $('#uFname').val();
        var last = $('#uLname').val();
        var phone = $('#uPhone').val();
        var email = $('#uEmail').val();
        console.log(name, last, phone, email);
        // create obj from vars
        var objToPost = {
            "fname": name,
            "lname": last,
            "email": email,
            "phone": phone
        }
        // ajax call to save
        var xhr = new XMLHttpRequest();
        xhr.open('PUT', 'https://315demo.firebaseio.com/contacts/' + contactToUpdate + '/.json', true);
        xhr.onload = function () { // success
            if (this.status >= 200 && this.status < 400) {
                //var myData = JSON.parse(this.response);
                console.log("PUT SUCCESS");

                getFirebaseContacts();
            }
            else { // error
                console.log("You have an error!!");
            }
        }
        var strObject = JSON.stringify(objToPost);
        xhr.send(strObject);

    }





    /// load data onload..
    getFirebaseContacts();


    //function to clear the results
    var clearResults = function () {
        $("#results").empty();
    }



    // expose public methods
    return {
        doAdd: addBuilder,
        doEdit: showEditDialog,
        doDelete: deleteBuilder,
        doAjax: getFirebaseContacts,
        doSave: updateFirebaseContact
    }
   

    


})();
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

//1
function myAJAX(callback, errorcb) {
    var xhr = new XLMHttpRequest();
    xhr.open('GET', 'https://315demo.firebaseio.com/contacts/', true);
    xhr.send();
    xhr.onload = function () {
        if (this.status >= 200 && this.status < 400) {
            if (callback && typeof (callback) == "function") {
                callback(this.response);
            }
            else {
                if (errorcb && typeof (errorcb) == "function") {
                    errorcb();
                }
                console.log("got it")
            }
        }
        
    }
} function taskOne() {
    myAJAX(function () { myfunction("Alert"), divWriter("this is a mutha-effin div") }, myerror);

}
function myfunction(msg) {
    alert(msg);

}
function myerror() {
    alert('error');
}
//2
function divWriter(str) {
    $('#mydiv').append(str);
}
divWriter("<p>Hey Baby</p>")
